package dk.simonvogensen.itodo.client;

import com.google.gwt.user.client.rpc.AsyncCallback;
import dk.simonvogensen.itodo.client.backend.Backend;
import dk.simonvogensen.itodo.server.TodoService;
import dk.simonvogensen.itodo.shared.model.Config;
import dk.simonvogensen.itodo.shared.model.TodoItem;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class BackendMock extends Backend {
    Config config;
    List<TodoItem> list = new ArrayList<TodoItem>();

    public BackendMock() {
    }

    public void createTodo(AsyncCallback<String> callback) {
        int id = list.size();
        callback.onSuccess("" + id);
    }

    public void deleteTodo(TodoItem item, AsyncCallback<Void> callback) {
        if(list.size() == 1) {
            callback.onFailure(new Exception("cant delete last item"));
        } else {
            list.remove(item);
            callback.onSuccess(null);
        }
    }

    public void getLatestTodoItem(AsyncCallback<TodoItem> callback) {
        callback.onSuccess(list.get(0));
    }

    public void importData(String importString, AsyncCallback<Void> callback) {
        list = TodoService.importData(importString, "sbv@lakeside.dk");
        callback.onSuccess(null);
    }

    public void updateConfig(Config config, AsyncCallback callback) {
        this.config = config;
        callback.onSuccess(null);
    }

    public void init() {
        config = new Config();
        TodoItem item = new TodoItem(config, "0", null, 0);
        item.setModified(true);
        list.add(item);
    }

    public void getTodoItemList(int startIndex, int fetchSize, AsyncCallback<List<TodoItem>> callback) {
        ArrayList<TodoItem> todoItems = new ArrayList<TodoItem>();
        TodoItem prevItem = null;
        int i1 = Math.max(0, list.size() - 1 - fetchSize);

        for (int i = list.size()-1-startIndex; i > i1; i--) {
            TodoItem todoItem = list.get(i);
            TodoItem t = new TodoItem(config, prevItem, todoItem.getId(), todoItem.getText(), todoItem.getIndex());
            todoItems.add(t);
            prevItem = t;
        }
        Collections.reverse(todoItems);
        callback.onSuccess(todoItems);
    }

    public void updateTodo(TodoItem item, AsyncCallback<Void> callback) {
        if(!list.contains(item)) list.add(0,item);
        callback.onSuccess(null);
    }
}